package com.dzl.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.dzl.config.exception.CommonException;
import com.dzl.constant.ChuanglanConstant;
import com.dzl.util.chuanglan.request.SmsSendRequest;
import com.dzl.util.chuanglan.response.SmsSendResponse;
import com.dzl.util.chuanglan.util.ChuangLanSmsUtil;
import com.dzl.util.chuanglan.util.UIDUtils;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.AlibabaAliqinFcSmsNumSendRequest;
import com.taobao.api.response.AlibabaAliqinFcSmsNumSendResponse;

public class SmsUtil {

    public SmsUtil() {
    }

    public static boolean sendSendVerCode(String code, String phone){
    	boolean isSuccess = false;
        TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
        AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
        req.setSmsType("normal");//短信类型
        req.setSmsFreeSignName("定制链");//短信签名
        req.setSmsParamString((new StringBuilder("{\"code\":\"")).append(code).append("\"}").toString());
        req.setRecNum(phone);//手机号码
        req.setSmsTemplateCode("SMS_12881742");//短信模板id
        try{
        	AlibabaAliqinFcSmsNumSendResponse response = client.execute(req);
            logger.info((new StringBuilder("sendSendVerCode-ret-->{code:"+code+"}")).append(response.getBody()).toString());
            if(response.isSuccess())
                isSuccess = response.isSuccess();
            else
                isSuccess = response.isSuccess();
        }catch(ApiException e){
            logger.error(e.getErrMsg());
        }
        return isSuccess;
    }
    
    
    /**
    *@Description:创蓝短信调用
    *@param content  发送内容
    *@param phone    发送的手机号
    *@return
    *boolean
    *@exception:
    *@author:pengkailun
    *@time:2021年3月5日下午3:18:00
     */
    public static boolean sendCLSms(String content, String phone){
//		String uId = UIDUtils.createUID();
        //通知类短信，上线后用这个
//		SmsSendRequest smsSingleRequest = new SmsSendRequest(ChuanglanConstant.MESSAGE_ACCOUNT, ChuanglanConstant.MESSAGE_PASSWORD,content, phone);
        //验证码类短信，上线前用
        SmsSendRequest smsSingleRequest = new SmsSendRequest(ChuanglanConstant.YZM_ACCOUNT, ChuanglanConstant.YZM_PASSWORD,content, phone);
      	String requestJson = JSON.toJSONString(smsSingleRequest);
      	logger.info("before request string is: " + requestJson);
    	String response = ChuangLanSmsUtil.sendSmsByPost(ChuanglanConstant.smsSingleRequestServerUrl, requestJson);
    	logger.info("response after request result is :" + response);
    	SmsSendResponse smsSingleResponse = JSON.parseObject(response, SmsSendResponse.class);
    	
		if(!smsSingleResponse.getCode().equals("0")) {
//			throw new CommonException(smsSingleResponse.getErrorMsg());
			logger.info(smsSingleResponse.getErrorMsg());
			return false;
		}else{
			return true;
		}
    }

    /**
     *@Description:创蓝短信调用
     *@param content  发送内容  通知类短信
     *@param phone    发送的手机号
     *@return
     *boolean
     *@exception:
     *@author:pengkailun
     *@time:2021年3月5日下午3:18:00
     */
    public static boolean sendCLSmsNotice(String content, String phone){
//		String uId = UIDUtils.createUID();
        //通知类短信，上线后用这个
		SmsSendRequest smsSingleRequest = new SmsSendRequest(ChuanglanConstant.MESSAGE_ACCOUNT, ChuanglanConstant.MESSAGE_PASSWORD,content, phone);
        //验证码类短信，上线前用
//        SmsSendRequest smsSingleRequest = new SmsSendRequest(ChuanglanConstant.YZM_ACCOUNT, ChuanglanConstant.YZM_PASSWORD,content, phone);
        String requestJson = JSON.toJSONString(smsSingleRequest);
        logger.info("before request string is: " + requestJson);
        String response = ChuangLanSmsUtil.sendSmsByPost(ChuanglanConstant.smsSingleRequestServerUrl, requestJson);
        logger.info("response after request result is :" + response);
        SmsSendResponse smsSingleResponse = JSON.parseObject(response, SmsSendResponse.class);

        if(!smsSingleResponse.getCode().equals("0")) {
//			throw new CommonException(smsSingleResponse.getErrorMsg());
            logger.info(smsSingleResponse.getErrorMsg());
            return false;
        }else{
            return true;
        }
    }

    /**
     * sendMsg:发送短信
     *
     * @param mobile     手机号码
     * @param templateId 模板id
     * @param context    模板上下文 eg:{"username":"xxx","ordername":"xxx","reason":"xxx"}
     *                   模板id	模板信息
     *                   SMS_baichun_3833	您好，我是${username}，我的订单${ordername},请尽快接单，谢谢。
     *                   SMS_baichun_3287	您好,我是${username},我的订单${ordername}请尽快生产,最迟发货时间为${time},谢谢!
     *                   SMS_baichun_3286	您好,我是${username},您的订单${ordername}我们将延迟生产,延迟生产原因:${reason}.
     *                   SMS_baichun_3285	您好,我是${username},您的订单${ordername}我们不能接单,不接单原因:${reason}.
     *                   SMS_baichun_3877	您好，订单#${ordername}#已到最迟发货时间，请及时发货。
     *                   SMS_baichun_3876	您好，订单#${ordername}#已发货，快递：${expressname} ，单号：${expressno} ，关注公众号“定制链”可在线查询物流信息。
     *                   SMS_36270114 		您好，很抱歉，您注册的定制链账户未通过审核，详情请联系客服。
     *                   SMS_36385136 		您好，您注册的定制链账户已经通过审核，请及时登录。
     *                   SMS_41545280		您好，订单 ${ordername} 已接单，关注公众号 "定制链" 可在线跟踪订单。
     *                   SMS_148862045		售后退款通知：订单“${orderName}”售后成功，金额${money}
     *                   SMS_148867011		催单通知：订单“${orderName}”，最迟发货时间${time}，请尽快接单
     *                   SMS_148862049		不接单通知：您的订单"${orderName}"被拒绝，原因“${reason}”，请及时查看
     *                   SMS_201653166		大客户忘记密码：验证码：${code}，您正在使用短信验证方式修改密码，请在30分钟内完成输入。
     * @return
     */
    public static boolean sendMsg(String mobile, String templateId, String context) {
        boolean isSuccess = false;
        TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
        AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
        req.setSmsType("normal");//短信类型
        req.setSmsFreeSignName("礼呗");//短信签名
        if ("SMS_201653166".equals(templateId)) {
            req.setSmsFreeSignName("礼呗");//短信签名
        }
        req.setSmsParamString(context);
        req.setRecNum(mobile);//手机号码
        req.setSmsTemplateCode(templateId);//短信模板id

        AlibabaAliqinFcSmsNumSendResponse rsp = null;
        try {
            rsp = client.execute(req);
            logger.info("sendMsg-ret-->" + rsp.getBody());
                isSuccess = rsp.isSuccess();
        } catch (ApiException e) {
            logger.error(e.getErrMsg());
        }
        return isSuccess;
    }

    public static void main(String args[])
            throws ApiException {
        System.out.println(sendMsg("13638659104", "SMS_201653166", "{\"code\":\"1235\"}"));
//        System.out.println(sendSendVerCode("123456","18986009421"));
    }

    private static String appkey = "23427230";
    private static String secret = "df5222d5ba58816c52639d0630d2d10e";
    private static String url = "http://gw.api.taobao.com/router/rest";
    private static Logger logger = LoggerFactory.getLogger(SmsUtil.class);

}
